import { useCallback, useEffect, useRef, useState } from "react";
import ReactPlayer from "react-player";
import {
  FullscreenExitOutlined,
  FullscreenOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
  SoundOutlined,
} from "@ant-design/icons";
// import type { MenuProps } from "antd";
import { Slider } from "antd";
import screenfull from "screenfull";

interface VideoPreviewProps {
  src: string;
  poster: string;
  width?: number;
  height?: number;
}

export default function VideoPreview({
  src: sourceSrc,
  poster,
  width = 280,
  height = 158,
}: VideoPreviewProps) {
  const playerRef = useRef<HTMLVideoElement | null>(null);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const controlsTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const [state, setState] = useState({
    src: undefined as string | undefined,
    playing: false,
    volume: 1,
    muted: false,
    played: 0,
    loaded: 0,
    playbackRate: 1.0,
    seeking: false,
    duration: 0,
    playedSeconds: 0,
    isFullscreen: false,
    showControls: false,
  });

  const [showVolumeSlider, setShowVolumeSlider] = useState(false);

  // 监听全屏变化事件
  useEffect(() => {
    const handleFullscreenChange = () => {
      const isFullscreen = screenfull.isEnabled && screenfull.isFullscreen;
      setState((prev) => ({ ...prev, isFullscreen }));

      // 退出全屏时暂停播放
      if (!isFullscreen && state.playing) {
        setState((prev) => ({ ...prev, playing: false }));
      }
    };

    if (screenfull.isEnabled) {
      screenfull.on("change", handleFullscreenChange);
    }

    return () => {
      if (screenfull.isEnabled) {
        screenfull.off("change", handleFullscreenChange);
      }
    };
  }, [state.playing]);

  // 控制条自动隐藏
  useEffect(() => {
    if (state.showControls && state.playing) {
      if (controlsTimeoutRef.current) {
        clearTimeout(controlsTimeoutRef.current);
      }
      controlsTimeoutRef.current = setTimeout(() => {
        setState((prev) => ({ ...prev, showControls: false }));
      }, 3000);
    }

    return () => {
      if (controlsTimeoutRef.current) {
        clearTimeout(controlsTimeoutRef.current);
      }
    };
  }, [state.showControls, state.playing]);

  // 点击封面图片开始播放并全屏
  const handlePosterClick = async () => {
    setState((prev) => ({ ...prev, src: sourceSrc, playing: true, showControls: true }));

    // 延迟进入全屏，等待视频加载
    setTimeout(() => {
      if (containerRef.current && screenfull.isEnabled) {
        screenfull.request(containerRef.current);
      }
    }, 100);
  };

  // 播放/暂停切换
  const handlePlayPause = () => {
    setState((prev) => ({ ...prev, playing: !prev.playing, showControls: true }));
  };

  // 音量调节
  const handleVolumeChange = (value: number) => {
    setState((prev) => ({
      ...prev,
      volume: value,
      muted: value === 0,
    }));
  };

  // 静音切换
  const handleToggleMuted = () => {
    setState((prev) => ({
      ...prev,
      muted: !prev.muted,
      volume: prev.muted ? 1 : 0,
    }));
  };

  // 倍速选择菜单
  // const playbackRateItems: MenuProps["items"] = [
  //   { key: "0.5", label: "0.5x" },
  //   { key: "0.75", label: "0.75x" },
  //   { key: "1", label: "1.0x (正常)" },
  //   { key: "1.25", label: "1.25x" },
  //   { key: "1.5", label: "1.5x" },
  //   { key: "2", label: "2.0x" },
  // ];

  // const handlePlaybackRateChange: MenuProps["onClick"] = ({ key }) => {
  //   setState((prev) => ({ ...prev, playbackRate: Number.parseFloat(key) }));
  // };

  // 全屏切换
  const handleToggleFullscreen = () => {
    if (!containerRef.current || !screenfull.isEnabled) return;

    if (screenfull.isFullscreen) {
      screenfull.exit();
    } else {
      screenfull.request(containerRef.current);
    }
  };

  // 进度条拖动
  const handleSeekChange = (value: number) => {
    setState((prev) => ({ ...prev, played: value / 100 }));
  };

  const handleSeekStart = () => {
    setState((prev) => ({ ...prev, seeking: true }));
  };

  const handleSeekEnd = (value: number) => {
    setState((prev) => ({ ...prev, seeking: false }));
    if (playerRef.current) {
      playerRef.current.currentTime = (value / 100) * playerRef.current.duration;
    }
  };

  // 鼠标移动显示控制条
  const handleMouseMove = () => {
    if (state.src) {
      setState((prev) => ({ ...prev, showControls: true }));
    }
  };

  // 时间格式化
  const formatTime = (seconds: number) => {
    if (!seconds || !Number.isFinite(seconds)) return "00:00";
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
  };

  const setPlayerRef = useCallback((player: HTMLVideoElement) => {
    if (!player) return;
    playerRef.current = player;
  }, []);

  const handleTimeUpdate = () => {
    const player = playerRef.current;
    if (!player || state.seeking || !player.duration) return;

    setState((prev) => ({
      ...prev,
      playedSeconds: player.currentTime,
      played: player.currentTime / player.duration,
    }));
  };

  const handleProgress = () => {
    const player = playerRef.current;
    if (!player || state.seeking || !player.buffered?.length) return;

    setState((prev) => ({
      ...prev,
      loaded: player.buffered?.end(player.buffered?.length - 1) / player.duration,
    }));
  };

  const handleDurationChange = () => {
    const player = playerRef.current;
    if (!player) return;
    setState((prev) => ({ ...prev, duration: player.duration }));
  };

  const {
    src,
    playing,
    volume,
    muted,
    played,
    playbackRate,
    isFullscreen,
    showControls,
    duration,
    playedSeconds,
  } = state;

  return (
    <div
      ref={containerRef}
      className="player-wrapper relative overflow-hidden rounded-lg"
      style={{ width, height }}
      onMouseMove={handleMouseMove}
      onMouseLeave={() => setState((prev) => ({ ...prev, showControls: false }))}
    >
      {/* 封面图片 - 只在未开始播放时显示 */}
      {!src && (
        <div
          className="absolute top-0 left-0 w-full h-full cursor-pointer z-10 group"
          onClick={handlePosterClick}
        >
          <img src={poster} alt="poster" className="w-full h-full object-cover" />
          <div className="absolute inset-0 bg-black/30 flex items-center justify-center group-hover:bg-black/40 transition-colors">
            <PlayCircleOutlined className="text-6xl text-white opacity-80 group-hover:opacity-100 group-hover:scale-110 transition-all" />
          </div>
        </div>
      )}

      {/* 视频播放器 */}
      {src && (
        <>
          <ReactPlayer
            ref={setPlayerRef}
            className="react-player"
            width="100%"
            height="100%"
            src={src}
            playing={playing}
            controls={false}
            playbackRate={playbackRate}
            volume={volume}
            muted={muted}
            onTimeUpdate={handleTimeUpdate}
            onProgress={handleProgress}
            onDurationChange={handleDurationChange}
            onEnded={() => setState((prev) => ({ ...prev, playing: false }))}
          />

          {/* 自定义控制条 */}
          <div
            className={`absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4 transition-opacity duration-300 
              ${showControls ? "opacity-100" : "opacity-0"}`}
          >
            {/* 进度条 */}
            <div className="mb-3">
              <Slider
                value={played * 100}
                onChange={handleSeekChange}
                onChangeComplete={handleSeekEnd}
                onFocus={handleSeekStart}
                tooltip={{ formatter: null }}
                trackStyle={{ backgroundColor: "#1890ff" }}
                railStyle={{ backgroundColor: "rgba(255, 255, 255, 0.3)" }}
              />
              <div className="flex justify-between text-xs text-white/80 mt-1">
                <span>{formatTime(playedSeconds)}</span>
                <span>{formatTime(duration)}</span>
              </div>
            </div>

            {/* 控制按钮 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                {/* 播放/暂停 */}
                <button
                  type="button"
                  onClick={handlePlayPause}
                  className="text-white text-2xl hover:text-blue-400 transition-colors"
                >
                  {playing ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
                </button>

                {/* 音量控制 */}
                <div
                  className="flex items-center gap-2"
                  onMouseEnter={() => setShowVolumeSlider(true)}
                  onMouseLeave={() => setShowVolumeSlider(false)}
                >
                  <button
                    type="button"
                    onClick={handleToggleMuted}
                    className="text-white text-2xl hover:text-blue-400 transition-colors"
                  >
                    <SoundOutlined />
                  </button>
                  {showVolumeSlider && (
                    <div className="w-20">
                      <Slider
                        value={muted ? 0 : volume * 100}
                        onChange={(value) => handleVolumeChange(value / 100)}
                        tooltip={{ formatter: (value) => `${value}%` }}
                        trackStyle={{ backgroundColor: "#1890ff" }}
                        railStyle={{ backgroundColor: "rgba(255, 255, 255, 0.3)" }}
                        className="m-0"
                      />
                    </div>
                  )}
                </div>

                {/* 倍速控制 */}
                {/* <Dropdown
                  menu={{ items: playbackRateItems, onClick: handlePlaybackRateChange }}
                  placement="top"
                >
                  <button
                    type="button"
                    className="text-white text-sm px-2 py-1 rounded hover:bg-white/20 transition-colors"
                  >
                    {playbackRate}x
                  </button>
                </Dropdown> */}
              </div>

              {/* 全屏按钮 */}
              <button
                type="button"
                onClick={handleToggleFullscreen}
                className="text-white text-2xl hover:text-blue-400 transition-colors"
              >
                {isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
